import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ButtonModule } from 'ng-devui/button';
import { AiService } from '../../services/ai.service';
import { I18nService } from '../../services/i18n.service';
import { ChatMessage } from '../../models/ai.model';
import { Nl2brPipe } from '../../pipes/nl2br.pipe';

@Component({
  selector: 'app-ai-assistant',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ButtonModule,
    Nl2brPipe
  ],
  templateUrl: './ai-assistant.component.html',
  styleUrl: './ai-assistant.component.scss'
})
export class AiAssistantComponent implements OnInit {
  isOpen = false;
  isMinimized = false;
  messages: ChatMessage[] = [];
  userInput = '';
  isLoading = false;
  
  // 预设问题
  quickQuestions = [
    '如何添加商品？',
    '如何编辑商品？',
    '如何删除商品？',
    '如何搜索商品？'
  ];

  constructor(
    private aiService: AiService,
    public i18n: I18nService
  ) {}

  ngOnInit(): void {
    // 添加欢迎消息
    this.addMessage({
      id: this.generateId(),
      role: 'assistant',
      content: '你好！我是电商后台管理系统的 AI 助手 🤖\n\n我可以帮您：\n• 解答系统使用问题\n• 生成商品描述\n• 提供操作指导\n\n有什么可以帮您的吗？',
      timestamp: new Date()
    });
  }

  /**
   * 切换聊天窗口
   */
  toggleChat(): void {
    this.isOpen = !this.isOpen;
    if (this.isOpen) {
      this.isMinimized = false;
      // 滚动到底部
      setTimeout(() => this.scrollToBottom(), 100);
    }
  }

  /**
   * 最小化窗口
   */
  minimizeChat(): void {
    this.isMinimized = !this.isMinimized;
  }

  /**
   * 关闭窗口
   */
  closeChat(): void {
    this.isOpen = false;
    this.isMinimized = false;
  }

  /**
   * 发送消息
   */
  sendMessage(content?: string): void {
    const messageContent = content || this.userInput.trim();
    
    if (!messageContent) {
      return;
    }

    // 添加用户消息
    const userMessage: ChatMessage = {
      id: this.generateId(),
      role: 'user',
      content: messageContent,
      timestamp: new Date()
    };
    this.addMessage(userMessage);

    // 清空输入框
    this.userInput = '';

    // 添加加载中的消息
    const loadingMessage: ChatMessage = {
      id: this.generateId(),
      role: 'assistant',
      content: '',
      timestamp: new Date(),
      isLoading: true
    };
    this.addMessage(loadingMessage);
    this.isLoading = true;

    // 调用 AI 服务
    this.aiService.chat(this.messages.filter(m => !m.isLoading)).subscribe({
      next: (response) => {
        // 移除加载消息
        this.messages = this.messages.filter(m => !m.isLoading);
        
        // 添加 AI 响应
        const aiMessage: ChatMessage = {
          id: this.generateId(),
          role: 'assistant',
          content: response.content,
          timestamp: new Date()
        };
        this.addMessage(aiMessage);
        this.isLoading = false;
      },
      error: (error) => {
        console.error('AI 响应错误:', error);
        this.messages = this.messages.filter(m => !m.isLoading);
        
        const errorMessage: ChatMessage = {
          id: this.generateId(),
          role: 'assistant',
          content: '抱歉，我遇到了一些问题。请稍后再试。',
          timestamp: new Date()
        };
        this.addMessage(errorMessage);
        this.isLoading = false;
      }
    });
  }

  /**
   * 点击快捷问题
   */
  selectQuickQuestion(question: string): void {
    this.sendMessage(question);
  }

  /**
   * 清空对话
   */
  clearChat(): void {
    this.messages = [];
    this.ngOnInit(); // 重新添加欢迎消息
  }

  /**
   * 添加消息到列表
   */
  private addMessage(message: ChatMessage): void {
    this.messages.push(message);
    setTimeout(() => this.scrollToBottom(), 100);
  }

  /**
   * 滚动到底部
   */
  private scrollToBottom(): void {
    const messagesContainer = document.querySelector('.chat-messages');
    if (messagesContainer) {
      messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }
  }

  /**
   * 生成唯一 ID
   */
  private generateId(): string {
    return `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  /**
   * 格式化时间
   */
  formatTime(date: Date): string {
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  }
}
